package com.flutter.jl_plugin

import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.util.Log
import com.flutter.jl_plugin.JlPlugin.Companion.channel
import com.flutter.jl_plugin.bluetooth.rscp.RcspEventHandleTask
import com.flutter.jl_plugin.constant.SConstant
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.jieli.bluetooth.bean.BleScanMessage
import com.jieli.bluetooth.bean.BluetoothOption
import com.jieli.bluetooth.bean.base.BaseError
import com.jieli.bluetooth.bean.base.CommandBase
import com.jieli.bluetooth.bean.command.custom.CustomCmd
import com.jieli.bluetooth.bean.device.eq.EqInfo
import com.jieli.bluetooth.bean.history.HistoryBluetoothDevice
import com.jieli.bluetooth.bean.parameter.CustomParam
import com.jieli.bluetooth.bean.response.ADVInfoResponse
import com.jieli.bluetooth.bean.response.ADVInfoResponse.KeySettings
import com.jieli.bluetooth.constant.BluetoothConstant
import com.jieli.bluetooth.constant.Command
import com.jieli.bluetooth.constant.ErrorCode
import com.jieli.bluetooth.constant.StateCode
import com.jieli.bluetooth.impl.rcsp.RCSPController
import com.jieli.bluetooth.interfaces.IActionCallback
import com.jieli.bluetooth.interfaces.bluetooth.RcspCommandCallback
import com.jieli.bluetooth.interfaces.rcsp.callback.BTRcspEventCallback
import com.jieli.bluetooth.interfaces.rcsp.callback.OnRcspActionCallback
import com.jieli.bluetooth.tool.DeviceAddrManager
import com.jieli.bluetooth.utils.CHexConver
import com.jieli.bluetooth.utils.CommandBuilder
import com.jieli.bluetooth.utils.JL_Log
import com.jieli.jl_bt_ota.util.BluetoothUtil
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.util.UUID


@SuppressLint("all")
object JlSdkPlugin : BTRcspEventCallback() , ActivityAware {
    private val TAG: String =
        JlSdkPlugin::class.java.getSimpleName()
    lateinit var context: Context
    val UUID_SERVICE = UUID.fromString("0000ae00-0000-1000-8000-00805f9b34fb")
    val UUID_WRITE = UUID.fromString("0000ae01-0000-1000-8000-00805f9b34fb")
    val UUID_NOTIFICATION = UUID.fromString("0000ae02-0000-1000-8000-00805f9b34fb")
    fun initSdk(call: MethodCall, result: MethodChannel.Result){
        if (!RCSPController.isInit()) {
            var map: Map<String,Any> = call.arguments as Map<String, Any>;
            var isUseMultiDevice=map["isUseMultiDevice"] as? Boolean ?: true;
            var timeoutMs=map["timeoutMs"] as? Int ?: 2000;
            var isLog=map["isLog"] as? Boolean ?: false;
            var isSaveFile=map["isSaveFile"] as? Boolean ?: false;
            var mtu=map["mtu"] as? Int ?: BluetoothConstant.BLE_MTU_MAX;
            var bleScanStrategy=map["bleScanStrategy"] as? Int ?: BluetoothConstant.NONE_FILTER;
            var serviceUUID=map["serviceUUID"]?.toString();
            var writeCharacteristicUUID=map["writeCharacteristicUUID"]?.toString();
            var notificationCharacteristicUUID=map["notificationCharacteristicUUID"]?.toString();
            val bluetoothOption = BluetoothOption.createDefaultOption() //创建默认配置
            bluetoothOption.setPriority(BluetoothOption.PREFER_BLE) //通信方式，支持ble和spp
                .setUseMultiDevice(isUseMultiDevice) //是否支持多设备管理
                .setTimeoutMs(timeoutMs) //命令超时时间, 默认2000ms
                .setMtu(mtu) //调节蓝牙MTU
                .setAutoConnectBle(false)
//                .setMandatoryUseBLE(true)
                .setReconnect(false)
                .setSupportCTKD(false)
                .setBleUUID(UUID_SERVICE, UUID_WRITE, UUID_NOTIFICATION)
                .setBleScanStrategy(bleScanStrategy)
            RCSPController.init(context, bluetoothOption)
            JL_Log.configureLog(context,isLog,isSaveFile)
            initRESCPCallBack()
            result.success(RCSPController.isInit())
        }else{
            result.success(true)
        }
    }

    fun initRESCPCallBack(){
        val rcspController = RCSPController.getInstance()
        rcspController.addBTRcspEventCallback(RcspEventHandleTask(rcspController))
//        rcspController.bluetoothManager.bluetoothOperation.registerBluetoothCallback(
//            SppBlueToothCallBack()
//        )
    }

    fun clearHistoryDeviceRecord(){
        //获取蓝牙操作对象
        val btManager = RCSPController.getInstance().bluetoothManager ?: return
        //自定义蓝牙实现，btManager为空
        //执行清除所有历史记录操作
        btManager.clearHistoryDeviceRecord()
    }

    //获取当前设备
    fun getCurrentDevices(call: MethodCall, result: MethodChannel.Result){
        val rcspController = RCSPController.getInstance()
        val usingDevice = rcspController.usingDevice
        if(usingDevice==null){
            val map = mapOf("result" to false)
            result.success(map)
        }else{
            val mapDevice: MutableMap<String, Any> = HashMap()
            mapDevice["address"] = usingDevice.getAddress()
            mapDevice["name"] = usingDevice.getName()
            val map = mapOf("result" to true,"device" to mapDevice)
            result.success(map)
        }
    }

    //蓝牙是否已连接
    fun isConnectioned(call: MethodCall, result: MethodChannel.Result){
        val rcspController = RCSPController.getInstance()
        val usingDevice = rcspController.usingDevice
        var isConneced=rcspController.isDeviceConnected(usingDevice);
        result.success(isConneced)
    }

    //蓝牙是否正在连接
    fun isConnecting(call: MethodCall, result: MethodChannel.Result){
        val rcspController = RCSPController.getInstance()
        result.success(rcspController.isConnecting)

    }

    fun isScanning(call: MethodCall, result: MethodChannel.Result){
        val rcspController = RCSPController.getInstance()
        result.success(rcspController.isScanning)
    }

    fun isInit(call: MethodCall, result: MethodChannel.Result){
        val rcspController = RCSPController.getInstance()
        result.success(rcspController.isRcspInit)
    }

    //获取历史设备
    fun getHistoryBluetoothDeviceList(call: MethodCall, result: MethodChannel.Result){
        val rcspController = RCSPController.getInstance()
        val list: List<HistoryBluetoothDevice> = rcspController.getHistoryBluetoothDeviceList()
        val mapDeviceListMap = ArrayList<Map<String, Any>>()
        list.forEach {
            val toJson = Gson().toJson(it)
            // 使用 TypeToken 获取 Map 类型
            val mapType = object : TypeToken<Map<String, Any>>() {}.type
            val map: Map<String, Any> = Gson().fromJson(toJson, mapType)
            mapDeviceListMap.add(map)
        }
        result.success(mapDeviceListMap)

    }

    //清空历史设备
    fun removeHistoryBluetoothDevice(call: MethodCall, result: MethodChannel.Result){
        var map: Map<String,Any> = call.arguments as Map<String, Any>;
        var mac=map["address"] as String
        val rcspController = RCSPController.getInstance()
        val list: List<HistoryBluetoothDevice> = rcspController.getHistoryBluetoothDeviceList()
        var currentDevice :HistoryBluetoothDevice?=null
        for (historyBluetoothDevice in list) {
            if(historyBluetoothDevice.address==mac){
                currentDevice=historyBluetoothDevice;
                break
            }
        }
        if(currentDevice!=null){
            rcspController.removeHistoryBtDevice(currentDevice!!,object :IActionCallback<HistoryBluetoothDevice>{
                override fun onSuccess(p0: HistoryBluetoothDevice?) {
                    result.success(true);

                }

                override fun onError(p0: BaseError?) {
                    result.success(false);
                }
            });
        }

    }



    fun startScanBlue(call: MethodCall, result: MethodChannel.Result){
        RCSPController.getInstance().removeBTRcspEventCallback(this)
        RCSPController.getInstance().addBTRcspEventCallback(this)
        RCSPController.getInstance().startBleScan(SConstant.SCAN_TIME);
        result.success(true)
    }

    fun stopScanBlue(call: MethodCall, result: MethodChannel.Result){
        RCSPController.getInstance().removeBTRcspEventCallback(this)
        RCSPController.getInstance().stopScan()
        result.success(true)

    }


    fun disconnectBlue(call: MethodCall, result: MethodChannel.Result){
        var map: Map<String,Any> = call.arguments as Map<String, Any>;
        var mac=map["address"] as String
        val device = BluetoothUtil.getRemoteDevice(mac)
        RCSPController.getInstance().disconnectDevice(device)
        result.success(true)
    }

    //停止重连
    fun stopReconnect(call: MethodCall, result: MethodChannel.Result){
        var op=RCSPController.getInstance().bluetoothManager.bluetoothOption
        op.setReconnect(false)
        var stopResult=RCSPController.getInstance().bluetoothManager.stopReconnect()
        RCSPController.getInstance().bluetoothManager.disconnect()
        result.success(stopResult)
    }

    //打开重连
    fun startReconnect(call: MethodCall, result: MethodChannel.Result){
        var op=RCSPController.getInstance().bluetoothManager.bluetoothOption
        op.setReconnect(true)
        result.success(true)
    }



    fun connectDevice(call: MethodCall, result: MethodChannel.Result){
//        var op=RCSPController.getInstance().bluetoothManager.bluetoothOption
//        op.setReconnect(true)
        var map: Map<String,Any> = call.arguments as Map<String, Any>;
        var mac=map["address"] as String
        var way=map["connectWay"] as Int
        //获取蓝牙操作对象
        var  btManager = RCSPController.getInstance().getBluetoothManager();
        if(btManager==null){
            val resultMap = mapOf(
                "code" to -1,
                "msg" to "btManager==null"
            )
            result.success(resultMap)
            return
        }
        if(btManager.bluetoothOperation.isConnecting){
            //设备正在连接
            val resultMap = mapOf(
                "code" to 2,
                "msg" to "设备正在连接"
            )
            result.success(resultMap)
            return;
        }
        val device = BluetoothUtil.getRemoteDevice(mac)
        if(device==null){
            //没发现该设备
            val resultMap = mapOf(
                "code" to -1,
                "msg" to "没发现该设备"
            )
            result.success(resultMap)
            return;
        }
        val resultMap = mapOf("code" to 1, "msg" to "操作成功")
        result.success(resultMap)
        DeviceAddrManager.getInstance().saveDeviceConnectWay(device,way)

        RCSPController.getInstance().connectDevice(device)
    }

    //按键设置
    fun setKeySetting(call: MethodCall, result: MethodChannel.Result){
        var map: Map<String,Any> = call.arguments as Map<String, Any>;
        val keyList = map.get("keySettingList")
        val gson = Gson()
        val type = object : TypeToken<List<KeySettings>>() {}.type
        val settingsList = gson.fromJson<List<KeySettings>>(gson.toJson(keyList), type)
        //获取RCSPController对象
        val controller = RCSPController.getInstance()
        //执行设置按键效果功能并等待结果回调
        controller.configKeySettings(
            controller.usingDevice,
            settingsList,
            object : OnRcspActionCallback<Int?> {
                override fun onSuccess(device: BluetoothDevice, message: Int?) {
                    //成功回调
                    //message - 结果码， 0为成功，其他为错误码
                    print("设置成功：${message}")
                    val mapOf = mutableMapOf<String, Any>()
                    if(message==0){
                        mapOf["code"]=1
                        mapOf["msg"]="success"
                        result.success(mapOf)
                    }else{
                        mapOf["code"]=message ?: 0
                        mapOf["msg"]="fail"
                        result.success(mapOf)
                    }


                }

                override fun onError(device: BluetoothDevice?, error: BaseError) {
                    //失败回调
                    //error - 错误信息
                    print("设置失败:${error.toString()}")
                    val mapOf = mutableMapOf<String, Any>()
                    mapOf["code"]=error.code;
                    mapOf["msg"]=error.message
                    result.success(mapOf)
                }
            })
    }

    fun findHistoryBluetoothDevice(call: MethodCall, result: MethodChannel.Result){
        var map: Map<String,Any> = call.arguments as Map<String, Any>;
        var mac=map["address"] as String
        val controller = RCSPController.getInstance()
        val findHistoryBluetoothDevice = controller.findHistoryBluetoothDevice(mac)
        val mapOf = mutableMapOf<String, Any>()

        if(findHistoryBluetoothDevice!=null){
            val toJson = Gson().toJson(findHistoryBluetoothDevice)
            Log.i(TAG, "findHistoryBluetoothDevice: ${toJson}")
            // 使用 TypeToken 获取 Map 类型
            val mapType = object : TypeToken<Map<String, Any>>() {}.type
            val map: Map<String, Any> = Gson().fromJson(toJson, mapType)
            Log.i(TAG, "findHistoryBluetoothDevice: map${map}")
            mapOf.put("device",map)
            mapOf.put("result",true)
            result.success(mapOf)
        }else{
            mapOf.put("result",false)
            result.success(mapOf)
        }

    }
    //获取设备设置信息
    fun getDevicesSetting(call: MethodCall, result: MethodChannel.Result){
        //int mask = 0x01; //属性掩码， 不能为0
        ////mask = 0xffffffff; //获取所有属性
        var map: Map<String,Any> = call.arguments as Map<String, Any>;
        var mask=map["mask"] as Long
        val maskInt = (mask and 0xFFFFFFFFL).toInt()
//        val device = BluetoothUtil.getRemoteDevice(mac)
        //获取RCSPController对象
        val controller = RCSPController.getInstance()
        var device=controller.btOperation.connectedDevice
        controller.getDeviceSettingsInfo(device,maskInt,object :OnRcspActionCallback<ADVInfoResponse>{
            override fun onSuccess(p0: BluetoothDevice?, p1: ADVInfoResponse) {
                val toJson = Gson().toJson(p1)
                var mapOf= mutableMapOf<String,Any>()
                mapOf["code"]=1;
                mapOf["msg"]="success"
                mapOf["advInfo"]=toJson
                result.success(mapOf)
            }

            override fun onError(p0: BluetoothDevice?, p1: BaseError) {
                var mapOf= mutableMapOf<String,Any>()
                mapOf["code"]=p1.code;
                mapOf["msg"]=p1.message
                result.success(mapOf)
            }

        })
    }

    //发送自定义指令
    fun sendCustomCmd(call: MethodCall, result: MethodChannel.Result){
        var map: Map<String,Any> = call.arguments as Map<String, Any>;
        var customData=map["customData"] as String
        //发送自定命令
        val data = CHexConver.hexStr2Bytes(customData) //自定义命令的附带数据
        val commandBase = CommandBuilder.buildCustomCmd(data)
        val rcspController = RCSPController.getInstance()
        rcspController.sendCommandAsync(rcspController.getUsingDevice(),commandBase,3000,object :
            RcspCommandCallback{
            override fun onCommandResponse(device: BluetoothDevice?, cmd: CommandBase<*, *>?) {
                if (cmd!!.status != StateCode.STATUS_SUCCESS) { //固件回复失败状态
                    val error = BaseError(
                        ErrorCode.SUB_ERR_RESPONSE_BAD_STATUS,
                        "Device response an bad status : " + cmd.status
                    )
                    error.setOpCode(Command.CMD_EXTRA_CUSTOM)
                    onErrCode(device, error)
                    return
                }
                //发送成功回调, 需要回复设备
                val customCmd = cmd as CustomCmd
                val response = customCmd.response
                if (null == response) {
                    Log.i("JlSdkPlugin", " \"发送自定义数据[%s]成功,没有回复数据!\",\n" + "${CHexConver.byte2HexStr(data)}")
                    return
                }
                val responseData = response.data //自定义回复数据

                Log.i("JlSdkPlugin", "\"发送自定义数据[%s]成功！！！\\n设备回复数据:[%s]\",\n" +
                        "                        ${CHexConver.byte2HexStr(data)}, ${CHexConver.byte2HexStr(responseData)}")
            }

            override fun onErrCode(p0: BluetoothDevice?, error: BaseError?) {
                Log.i("JlSdkPlugin", "\"发送自定义数据[%s]失败！！！\\n错误原因: %s\", ${CHexConver.byte2HexStr(data)}, ${error}")
            }
        })
    }

    //修改按键
    fun modifyHeadsetFunctions(call: MethodCall, result: MethodChannel.Result){
        val rcspController = RCSPController.getInstance()
        val usingDevice = rcspController.usingDevice
        var map: Map<String,Any> = call.arguments as Map<String, Any>;
        val intList = map["params"] as? List<Int> ?: emptyList()
        val params = ByteArray(intList.size) { i -> intList[i].toByte() }
        var type=map["type"] as Int;
        rcspController.modifyDeviceSettingsInfo(usingDevice,type,params,object :OnRcspActionCallback<Int>{
            override fun onSuccess(p0: BluetoothDevice?, message: Int?) {
                val map = mapOf("result" to true, "message" to "${message}")
                result.success(map);
            }

            override fun onError(p0: BluetoothDevice?, p1: BaseError?) {
                val map = mapOf("result" to false, "error" to "${p1?.message}")
                result.success(map);
            }

        })
    }

    //修改蓝牙名字
    fun changeDeviceName(call: MethodCall, result: MethodChannel.Result){
        var map: Map<String,Any> = call.arguments as Map<String, Any>;
        var deviceName=map["name"].toString()
        val rcspController = RCSPController.getInstance()
        rcspController.configDeviceName(rcspController.usingDevice,deviceName,object :OnRcspActionCallback<Int>{
            override fun onSuccess(p0: BluetoothDevice?, message: Int?) {
                val map = mapOf("code" to 1, "msg" to "success")
                result.success(map)
            }

            override fun onError(p0: BluetoothDevice?, p1: BaseError?) {
                val map = mapOf("code" to -1, "msg" to "${p1?.message}")
                result.success(map)
            }

        })
    }

    //重启设备
    fun rebootDevice(call: MethodCall, result: MethodChannel.Result){
        val rcspController = RCSPController.getInstance()
        rcspController.rebootDevice(rcspController.usingDevice,object :OnRcspActionCallback<Boolean>{
            override fun onSuccess(p0: BluetoothDevice?, p1: Boolean?) {
                val map = mapOf("code" to 1, "msg" to "success")
                result.success(map)
            }

            override fun onError(p0: BluetoothDevice?, p1: BaseError?) {
                val map = mapOf("code" to -1, "msg" to "${p1?.message}")
                result.success(map)
            }

        })
    }


    override fun onDiscoveryStatus(bBle: Boolean, bStart: Boolean) {
        super.onDiscoveryStatus(bBle, bStart)
    }

    fun isPatternAtPosition(data: ByteArray, startIndex: Int, pattern: ByteArray): Boolean {
        if (startIndex + pattern.size > data.size) return false
        for (i in pattern.indices) {
            if (data[startIndex + i] != pattern[i]) return false
        }
        return true
    }

    override fun onDiscovery(device: BluetoothDevice?, bleScanMessage: BleScanMessage?) {
        super.onDiscovery(device, bleScanMessage)
        device?.let {
            bleScanMessage?.let {
                val data = bleScanMessage.rawData
                val pattern = byteArrayOf(0x22.toByte(), 0xB8.toByte(), 0x00.toByte(), 0x08.toByte())
                val isMatch = isPatternAtPosition(data, 2, pattern)
                if (isMatch) {
                    val devType =bleScanMessage?.deviceType //设备类型
                    val action =bleScanMessage?.action //活动
                    val edrAddress=bleScanMessage?.edrAddr //广播地址
                    val name = device.name ?: "Unknown"
                    val address = device.address ?: "Unknown"
                    val rssi = bleScanMessage?.rssi ?: 0
                    val connectWay = bleScanMessage?.connectWay ?: 0

                    Log.i("BlueSearch", "onDiscovery: name=$name, address=$address, rssi=$rssi ,devType=$devType edrAddress=$edrAddress action=$action")

                    val result = mapOf(
                        "name" to name,
                        "address" to address,
                        "rssi" to rssi,
                        "devType" to devType,
                        "action" to action,
                        "edrAddress" to edrAddress,
                        "connectWay" to connectWay

                    )

                    JlPlugin.channel?.invokeMethod("blueDevice", result)
                } else {
                    Log.d("TAG", "在位置2不是 22 B8 00 08")
                }
            }


        }
    }
    //设备指令响应
    override fun onDeviceCommand(device: BluetoothDevice, cmd: CommandBase<*, *>) {

        super.onDeviceCommand(device, cmd)
        if(cmd.id== Command.CMD_EXTRA_CUSTOM){
            JL_Log.e(TAG, "收到命令：$cmd")
            //处理固件向App发送的自定义命令。
            //处理固件向App发送的自定义命令。
            val customCmd = cmd as CustomCmd
            val param = customCmd.param
            val isNeedResponse = (cmd.getType() == CommandBase.FLAG_HAVE_PARAMETER_AND_RESPONSE || cmd.getType() == CommandBase.FLAG_NO_PARAMETER_AND_RESPONSE)
            if (null == param) {
                if (isNeedResponse) { //需要回复
                    val responseData = ByteArray(0) //可以设置回复的数据
                    customCmd.setParam(CustomParam(responseData))
                    customCmd.setStatus(StateCode.STATUS_SUCCESS)
                    RCSPController.getInstance().sendCommandResponse(device, customCmd, null) //发送命令回复
                }
                JL_Log.i(TAG,"接收到设备发送的自定义数据: 无参数。错误的命令数据格式")
                return
            }
            val data = param.data //自定义数据
            //parseCustomData(data);
            JL_Log.i(TAG,"接收到设备发送的自定义数据:\n${CHexConver.byte2HexStr(data)}")
            if (isNeedResponse) { //需要回复
                val responseData = ByteArray(0) //可以设置回复的数据
                if (responseData.size > 0) {
                    JL_Log.i(TAG,"回复设备的自定义数据:\n${CHexConver.byte2HexStr(data)}，${CHexConver.byte2HexStr(responseData)}")

                }
                customCmd.setParam(CustomParam(responseData))
                customCmd.setStatus(StateCode.STATUS_SUCCESS)
                RCSPController.getInstance().sendCommandResponse(device, customCmd, null) //发送命令回复
            }
        }
    }

    //eq设置
    fun eqSetting(call: MethodCall, result: MethodChannel.Result){
        val mRCSPController = RCSPController.getInstance()
        if(mRCSPController.isDeviceConnected){
            //设备已连接
            var map: Map<String,Any> = call.arguments as Map<String, Any>;
            val intList = map["value"] as? List<Int> ?: emptyList()
            val byteArray = ByteArray(intList.size) { i -> intList[i].toByte() }
            val eqInfo = EqInfo()
            eqInfo.mode=map["mode"] as Int;
            eqInfo.isDynamic=map["dynamic"] as Boolean;
            eqInfo.freqs=(map["freqs"] as List<Int>).toIntArray()
            eqInfo.value=byteArray
            mRCSPController.configEqInfo(mRCSPController.getUsingDevice(),eqInfo,object :OnRcspActionCallback<Boolean>{
                override fun onSuccess(p0: BluetoothDevice?, p1: Boolean?) {
                    JL_Log.i(TAG,"EQ设置成功")
                    result.success(true)
                }

                override fun onError(p0: BluetoothDevice?, p1: BaseError?) {
                    JL_Log.i(TAG,"EQ设置失败")
                    result.success(false)
                }
            })
        }
    }

    //获取EQ设置
    fun getEQSetting(call: MethodCall, result: MethodChannel.Result){
        val mRCSPController = RCSPController.getInstance()
        mRCSPController.getEqInfo(mRCSPController.usingDevice,object :OnRcspActionCallback<Boolean>{
            override fun onSuccess(device: BluetoothDevice, p1: Boolean) {
                //成功回调
                //结果将会在BTRcspEventCallback#onEqPresetChange、BTRcspEventCallback#onEqChange回调
                JL_Log.i(TAG,"getEQSetting:onSuccess:${p1}")
            }

            override fun onError(p0: BluetoothDevice?, p1: BaseError?) {
                JL_Log.e(TAG,"getEQSetting:onError:${p1.toString()}")
            }

        })
    }

    fun startRecord(call: MethodCall, result: MethodChannel.Result){
        val mRCSPController = RCSPController.getInstance()
        if(!mRCSPController.isDeviceConnected){
            result.success(false)
        }else{
            _changeRecordStatus(true,result)
        }

    }

    fun stopRecord(call: MethodCall, result: MethodChannel.Result){
        val mRCSPController = RCSPController.getInstance()
        if(!mRCSPController.isDeviceConnected){
            result.success(false)
        }else{
            _changeRecordStatus(false,result)
        }
    }

    fun _changeRecordStatus(isStart: Boolean, result: MethodChannel.Result){
        //发送自定命令
        val data = CHexConver.hexStr2Bytes(if(isStart)"07fe01" else "07fe00") //自定义命令的附带数据
        val commandBase = CommandBuilder.buildCustomCmd(data)
        val rcspController = RCSPController.getInstance()
        rcspController.sendCommandAsync(rcspController.getUsingDevice(),commandBase,3000,object :
            RcspCommandCallback{
            override fun onCommandResponse(device: BluetoothDevice?, cmd: CommandBase<*, *>?) {
                result.success(true)
            }

            override fun onErrCode(p0: BluetoothDevice?, error: BaseError?) {
                Log.i("JlSdkPlugin", "\"发送自定义数据[%s]失败！！！\\n错误原因: %s\", ${CHexConver.byte2HexStr(data)}, ${error}")
                result.success(false)
            }
        })
    }


    override fun onDiscovery(device: BluetoothDevice?) {
        super.onDiscovery(device)
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        Log.i("JlSdkPlugin", "onAttachedToActivity: ${binding.getActivity().javaClass.simpleName}")
    }

    override fun onDetachedFromActivityForConfigChanges() {
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    }

    override fun onDetachedFromActivity() {
    }


}